package com.vagavaga.tx;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import org.apache.log4j.Logger;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public final class Tx {
    private static final Logger log = Logger.getLogger(Tx.class);

    public static DataSource bind(String name, DataSource ds) {
        return DataSourceRegistry.instance().put(name, ds);
    }

    public static DataSource unbind(String name) {
        return DataSourceRegistry.instance().unbind(name);
    }

    public static Connection connection(String name, TransactionAttribute txtype) throws SQLException {
        return txtype.connection(name);
    }

    public static void rollback(Connection conn) {
        if (conn != null) {
            try {
                conn.rollback();
            } catch (SQLException sqle) {
                log.debug("Could not rollback transaction", sqle);
            }
        }
    }

    public static void close(Statement stm) {
        if (stm != null) {
            try {
                stm.close();
            } catch (SQLException sqle) {
                log.debug("Could not close statement.", sqle);
            }
        }
    }

    public static void close(Connection conn) {
        if (conn != null) {
            try {
                if (!conn.isClosed()) {
                    _close(conn);
                }
            } catch (SQLException e) {
                log.debug("Failed to query closed state of connection.", e);
            }
        }
    }

    private static void _close(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                log.debug("Failed to close connection.", e);
            }
        }
    }

    public static DataSource createPoolable(String driverClass, String jdbcUrl, String user, String password)
            throws PropertyVetoException {
        ComboPooledDataSource cpds = new ComboPooledDataSource();
        cpds.setDriverClass(driverClass); // loads the jdbc driver
        cpds.setJdbcUrl(jdbcUrl);
        cpds.setUser(user);
        cpds.setPassword(password);
        return cpds;
    }

    public static void close(ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                log.debug("Failed to close result set!", e);
            }
        }
    }
}
